<?php

namespace app\middleware;


use app\support\JwtHelper;
use app\support\ResponseHelper;
use Illuminate\Support\Facades\Log;
use Tinywan\Jwt\JwtToken;
use Webman\Http\Request;
use Webman\Http\Response;
use Webman\MiddlewareInterface;

class AuthCheck implements MiddlewareInterface
{
    private $excludeUrl = array(
        array("url" => "/api/employee/login", "method" => "POST"),
        array("url" => "/user/user/login", "method" => "POST"),
        array("url" => "/user/user/login", "method" => "GET"),
        array("url" => "/user/shop/status", "method" => "GET")
    );
    public function process(Request $request, callable $handler): Response
    {
        if ($this->skipVerify()) {
            return $handler($request);
        } else {
            $token = $request->header("Token") ?: $request->header("authentication");
            if (!$token || !JwtHelper::verify($token)) {
                return  ResponseHelper::failJson("登录失效");
            }
            return $handler($request);
        }
    }

    public function skipVerify(): bool
    {
        return collect($this->excludeUrl)
            ->where("url", "=", \request()->uri())
            ->where("method", "=", \request()->method())
            ->isNotEmpty();
    }
}